package com.uit.trip.bridge;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.uit.trip.models.CommentItem;
import com.uit.trip.models.ImageDictionary;
import com.uit.trip.models.Trip;
import com.uit.trip.tab_activity.Tab_TripHomeActivity;
import com.uit.trip.tab_activity.Tab_TripLocationActivity;
import com.uit.trip.tab_activity.Tab_TripSearchActivity;
import com.uit.trip.tab_activity.childs.CommentActivity;

public class Server {

	private static final String SERVER_USER_INFO = "http://125.253.122.16/ws/api/login";// "http://http://125.253.122.16:1096/TripTracker.aspx/trip/user";
	private static final String SERVER_UPLOAD_PHOTO = "http://125.253.122.16/ws/api/upimg";// "http://http://125.253.122.16:1096/TripTracker.aspx/trip/upload";
	private static final String SERVER_GETLISTIMAGES = "http://125.253.122.16/ws/api/getlist";// "http://http://125.253.122.16:1096/TripTracker.aspx/getListImage";
	private static final String SERVER_SENDCOMMENT = "http://125.253.122.16/ws/api/postcomment";// "http://http://125.253.122.16:1096/TripTracker.aspx/trip/comment";
	private static final String SERVER_GETLISTCOMMENT = "http://125.253.122.16/ws/api/getlistcomment";// "http://http://125.253.122.16:1096/TripTracker.aspx/trip/getListComments";
	private static final String SERVER_GETTOTALLIKES = "http://125.253.122.16/";// "http://http://125.253.122.16:1096/TripTracker.aspx/trip/getTotalLikes";
	private static final String SERVER_GETLISTUSERLIKES = "http://125.253.122.16/ws/api/getlistlike";// "http://http://125.253.122.16:1096/TripTracker.aspx/trip/getListUserLikes";
	private static final String SERVER_SEND_LIKE = "http://125.253.122.16/ws/api/postlike";
	private static final String SERVER_GET_ITEM = "http://125.253.122.16/ws/api/getitem";
	private static final String SERVER_GETLISTLOCATIONS = "http://125.253.122.16/ws/api/getlistlocation";
	private static final String FACEBOOK = "https://graph.facebook.com/me/photos?access_token=";
	public static final String LINKSHARE = "http://125.253.122.16/post/detail/id/";
	private static final String SERVER_SEARCH = "http://125.253.122.16/ws/api/search";

	private AsyncHttpClient client = new AsyncHttpClient();
	private Context context;

	public Server() {

	}

	public Server(Context mContext) {
		this.context = mContext;
	}

	public void postImageToFacebook(Bitmap bitmap, String accessToken) {
		String linkServer = FACEBOOK + accessToken;
		Log.i("duongnx", "access:" + linkServer);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 50, bos);
		byte[] data = bos.toByteArray();

		File f = new File(context.getCacheDir(), "test");
		try {
			f.createNewFile();
			FileOutputStream fos = new FileOutputStream(f);
			fos.write(data);
			fos.flush();
			fos.close();

			RequestParams params = new RequestParams();
			// params.put("access_token", accessToken);
			params.put("source", f);

			client.post(linkServer, params, new AsyncHttpResponseHandler() {

				@Override
				public void onFinish() {
					// TODO Auto-generated method stub
					super.onFinish();
				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					// TODO Auto-generated method stub
					super.onFailure(arg0, arg1);
					Log.i("duongnx", "postimage to facebook fail:" + arg1
							+ arg0);
				}

				@Override
				public void onSuccess(String response) {
					// TODO Auto-generated method stub
					super.onSuccess(response);
					Log.i("duongnx", "postimage to facebook success:"
							+ response);
				}

			});
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.i("duongnx", "error file");
		}
	}

	/*
	 * Post user info to server
	 */
	public void postUserInfo(String userId, String userName, String email) {
		RequestParams params = new RequestParams();
		params.put("id", userId);
		params.put("name", userName);
		params.put("email", email);

		client.post(SERVER_USER_INFO, params, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(Throwable e, String error) {
				// TODO Auto-generated method stub
				super.onFailure(e, error);
				Intent i = new Intent(Tab_TripHomeActivity.POST_USERINFO_FINISH);
				i.putExtra("result", false);
				context.sendBroadcast(i);
			}

			@Override
			public void onSuccess(String response) {
				// TODO Auto-generated method stub
				super.onSuccess(response);
				Intent i = new Intent(Tab_TripHomeActivity.POST_USERINFO_FINISH);
				i.putExtra("result", true);
				context.sendBroadcast(i);
			}

		});
	}

	/*
	 * 
	 */
	// public void postPhoto(String userId, String _description, String _la,
	// String _lng, String imagePath) {
	//
	// RequestParams params = new RequestParams();
	// params.put("id", userId);
	// // params.put("name", userName);
	// // params.put("time", time);
	// params.put("description", _description);
	// params.put("la", _la);
	// params.put("lng", _lng);
	//
	// File image = new File(imagePath);
	// // post(SERVER, imagePath);
	// try {
	// params.put("image", image);
	// } catch (Exception e) {
	// // TODO: handle exception
	// }
	// client.post(SERVER_UPLOAD_PHOTO, params, null);
	// }

	public void postPhoto(String userId, String _description, String _la,
			String _lng, String _address, String imagePath) {

		final Trip trip = new Trip(userId, "", "", _description, imagePath,
				_la, _lng, "", 0);
		RequestParams params = new RequestParams();
		params.put("id", userId);
		// params.put("name", userName);
		// params.put("time", time);
		params.put("description", _description);
		params.put("la", _la);
		params.put("lng", _lng);
		params.put("address", _address);
		File image = new File(imagePath);
		// post(SERVER, imagePath);
		try {
			params.put("image", image);
		} catch (Exception e) {
			// TODO: handle exception
		}

		Log.i("duongnx", "upload link:" + SERVER_UPLOAD_PHOTO);
		client.post(SERVER_UPLOAD_PHOTO, params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(Throwable e, String arg1) {
						// TODO Auto-generated method stub
						super.onFailure(e, arg1);
						Log.i("duongnx", "upload fail:" + e + " =" + arg1);
						Intent i = new Intent(
								Tab_TripHomeActivity.POST_IMAGE_FINISH);
						i.putExtra("result", false);
						context.sendBroadcast(i);
					}

					@Override
					public void onSuccess(String response) {
						// TODO Auto-generated method stub
						super.onSuccess(response);
						Intent i = new Intent(
								Tab_TripHomeActivity.POST_IMAGE_FINISH);
						Log.i("duongnx", "upload success:" + response);
						if (response.contains("false")) {
							i.putExtra("result", false);
						} else {
							ImageDictionary dic = Parser
									.parseImageUploadInfo(response);
							if (dic == null)
								return;
							i.putExtra("result", true);
							i.putExtra("description", trip.description);
							i.putExtra("la", trip.la);
							i.putExtra("lng", trip.lng);
							i.putExtra("imgId", dic.imgId);
							i.putExtra("link", dic.link);
							i.putExtra("date", dic.date);
						}
						context.sendBroadcast(i);
					}

				});
	}

	public void getListImages(String imgId, String userId) {
		RequestParams params = new RequestParams();
		params.put("img_id", imgId);
		params.put("user_id", userId);

		client.get(SERVER_GETLISTIMAGES, params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(Throwable arg0, String arg1) {
						// TODO Auto-generated method stub
						super.onFailure(arg0, arg1);
						Log.i("duongnx", "get list fail:" + arg1);
						Intent i = new Intent(
								Tab_TripHomeActivity.NEW_IMAGELIST_FOUND);
						i.putExtra("response", "");
						context.sendBroadcast(i);
					}

					@Override
					public void onSuccess(String response) {
						// TODO Auto-generated method stub
						super.onSuccess(response);

						Intent i = new Intent(
								Tab_TripHomeActivity.NEW_IMAGELIST_FOUND);
						i.putExtra("response", response);
						context.sendBroadcast(i);
					}

				});
	}

	public void postComment(String imageId, String userId, CommentItem item) {
		RequestParams params = new RequestParams();
		params.put("img_id", imageId);
		params.put("user_id", userId);
		params.put("comment", item.comment);
		// params.put("date", item.date);

		client.post(SERVER_SENDCOMMENT, params, null);
	}

	public void getListComments(String imageId) {
		RequestParams params = new RequestParams();
		params.put("img_id", imageId);

		client.get(SERVER_GETLISTCOMMENT, params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(Throwable arg0, String arg1) {
						// TODO Auto-generated method stub
						super.onFailure(arg0, arg1);
						Log.i("duongnx", "onFail");
					}

					@Override
					public void onSuccess(String response) {
						// TODO Auto-generated method stub
						super.onSuccess(response);
						// Log.i("duongnx", "getListComment:" + response);
						Intent i = new Intent(
								CommentActivity.FINISH_LOADING_COMMENTS);
						i.putExtra("response", response);
						context.sendBroadcast(i);
					}

				});
	}

	public void postLike(String imgId, String userId) {
		RequestParams params = new RequestParams();
		params.put("img_id", imgId);
		params.put("user_id", userId);

		client.post(SERVER_SEND_LIKE, params, null);
	}

	public void getListUserLikes(String imageId) {
		RequestParams params = new RequestParams();
		params.put("img_id", imageId);

		client.get(SERVER_GETLISTUSERLIKES, params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(Throwable arg0, String arg1) {
						// TODO Auto-generated method stub
						super.onFailure(arg0, arg1);
						Log.i("duongnx", "onFail");
					}

					@Override
					public void onSuccess(String response) {
						// TODO Auto-generated method stub
						super.onSuccess(response);
						// Log.i("duongnx", "getListUserLike:" + response);
						Intent i = new Intent(
								CommentActivity.FINISH_LOADING_LIKES);
						i.putExtra("response", response);
						context.sendBroadcast(i);
					}

				});
	}

	public void getListLocations(String la, String lng, String userId) {

		RequestParams params = new RequestParams();
		params.put("la", la);
		params.put("lng", lng);
		params.put("user_id", userId);
		params.put("limit", "5");

		client.get(SERVER_GETLISTLOCATIONS, params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(Throwable arg0, String arg1) {
						// TODO Auto-generated method stub
						super.onFailure(arg0, arg1);
						Log.i("duongnx", "getListLocation fail:" + arg0 + ":"
								+ arg1);
						Intent i = new Intent(
								Tab_TripLocationActivity.NEW_LIST_LOCATIONS);
						i.putExtra("result", false);
						context.sendBroadcast(i);
					}

					@Override
					public void onSuccess(String arg0) {
						// TODO Auto-generated method stub
						super.onSuccess(arg0);

						Intent i = new Intent(
								Tab_TripLocationActivity.NEW_LIST_LOCATIONS);
						i.putExtra("result", true);
						i.putExtra("response", arg0);
						context.sendBroadcast(i);
					}
				});
	}

	public void getLisSearch(String userId, String searchStr) {
		String search = searchStr.replace(" ", "+");

		RequestParams params = new RequestParams();
		params.put("s", search);
		params.put("user_id", userId);

		client.get(SERVER_SEARCH, params, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(Throwable arg0, String arg1) {
				// TODO Auto-generated method stub
				super.onFailure(arg0, arg1);
				Log.i("duongnx", "Search fail:" + arg0);
				Intent i = new Intent(Tab_TripSearchActivity.SEARCH_NEW);
				i.putExtra("result", false);
				context.sendBroadcast(i);
			}

			@Override
			public void onSuccess(String arg0) {
				// TODO Auto-generated method stub
				super.onSuccess(arg0);

				Intent i = new Intent(Tab_TripSearchActivity.SEARCH_NEW);
				i.putExtra("result", true);
				i.putExtra("response", arg0);
				context.sendBroadcast(i);
			}

		});
	}
}